<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket H.264视频流演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
        }
        .player-wrapper {
            margin: 20px auto;
            max-width: 800px;
        }
        #player {
            width: 100%;
            background-color: #000;
        }
        .form-control {
            margin: 10px 0;
            padding: 8px;
            width: 80%;
            max-width: 550px;
        }
        button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        #startBtn {
            background-color: #4CAF50;
            color: white;
        }
        #stopBtn {
            background-color: #f44336;
            color: white;
        }
        #status {
            margin-top: 20px;
            padding: 10px;
            border-radius: 5px;
        }
        .streaming {
            background-color: #d4edda;
            color: #155724;
        }
        .stopped {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/ovenplayer/dist/ovenplayer.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <h1>WebSocket H.264视频流演示</h1>

    <div class="player-wrapper">
        <div id="player"></div>
    </div>

    <div>
        <button type="button" style="min-width: 550px;" onclick="loadPlayer()">
            <i class="fas me-2 fa-play"></i> LOAD PLAYER
        </button>
        <button type="button" style="min-width: 550px;" onclick="unLoadPlayer()">
            <i class="fas me-2 fa-stop"></i> UNLOAD PLAYER
        </button>
    </div>
    
    <div>
        <input type="text" id="playbackUrl" class="form-control" placeholder="输入流地址 (ws:// 或 wss://)">
        <button type="button" style="min-width: 120px;" onclick="changeSource()">CHANGE SOURCE</button>
    </div>
   

    <div>
        <input type="text" id="streamKey" placeholder="输入流密钥" value="stream1">
        <button id="startBtn">开始推流</button>
        <button id="stopBtn">停止推流</button>
    </div>
    
    <div id="status" class="stopped">状态: 未推流</div>
    <div id="messages"></div>

    <script>
        let player = null;
        const playerOption = {
            autoStart: true,
            autoFallback: true,
            mute: false,
            sources: []
        };

        function unLoadPlayer() {
            if (player) {
                player.remove();
                player = null;
                console.log('播放器已卸载');
            }
        }

        function loadPlayer() {
            if (player) {
                unLoadPlayer();
            }

            if (playerOption.sources.length === 0) {
                alert('请先添加播放源');
                return;
            }

            player = OvenPlayer.create('player', playerOption);

            player.on('ready', function() {
                console.log('播放器准备就绪');
            });

            player.on('error', function(error) {
                console.error('播放器错误:', error);
                alert('播放错误: ' + error.message);
            });
        }
        
        function changeSource() {
            const urlInput = document.getElementById('playbackUrl');
            const url = urlInput.value.trim();

            if (!url) {
                alert('请输入有效的流地址');
                return;
            }

            let protocol;
            if (url.startsWith('ws:') || url.startsWith('wss:')) {
                protocol = "webrtc";
            } else if (url.endsWith('.m3u8')) {
                protocol = url.endsWith('llhls.m3u8') ? 'll-hls' : 'hls';
            } else if (url.endsWith('.mpd')) {
                protocol = "dash";
            } else if (url.endsWith('.mp4')) {
                protocol = "http";
            } else {
                alert('不支持的流协议');
                return;
            }

            // 清空原有源
            playerOption.sources = [{
                type: protocol,
                file: url
            }];

            console.log('源已更新:', playerOption.sources);
            
            // 如果播放器已存在，重新加载
            if (player) {
                loadPlayer();
            }
        }
    </script>

     <script>
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const statusDiv = document.getElementById('status');
        const messagesDiv = document.getElementById('messages');
        const streamKeyInput = document.getElementById('streamKey');
        
        let eventSource = null;

        startBtn.addEventListener('click', startStream);
        stopBtn.addEventListener('click', stopStream);

        let streamActive = false;

        async function startStream() {
            const streamKey = streamKeyInput.value.trim();
            if (!streamKey) {
                alert('请输入流密钥');
                return;
            }

            if (streamActive) {
                alert('已有推流正在进行');
                return;
            }

            try {
                // 初始化EventSource
                eventSource = new EventSource(`http://127.0.0.1:8080/start-stream?streamKey=${encodeURIComponent(streamKey)}`);
                
                streamActive = true;
                updateUI(true, streamKey);
                addMessage('正在连接推流服务器...');

                // 事件处理器
                eventSource.onopen = () => {
                    addMessage('连接已建立');
                };

                eventSource.onmessage = (e) => {
                    handleServerMessage(e.data, streamKey);
                };

                eventSource.onerror = () => {
                    addMessage('连接错误');
                    cleanupStream();
                };

            } catch (error) {
                addMessage(`错误: ${error.message}`);
                cleanupStream();
            }
        }

        function handleServerMessage(message, streamKey) {
            addMessage(message);
            
            if (message.includes('started')) {
                updateUI(true, streamKey);
            } else if (message.includes('ended')) {
                cleanupStream();
            } else if (message.includes('error')) {
                addMessage('推流错误: ' + message);
                cleanupStream();
            }
        }

        function updateUI(isStreaming, streamKey) {
            if (isStreaming) {
                statusDiv.textContent = `状态: 正在推流 (${streamKey})`;
                statusDiv.className = 'status streaming';
                startBtn.disabled = true;
                stopBtn.disabled = false;
            } else {
                statusDiv.textContent = '状态: 未推流';
                statusDiv.className = 'status stopped';
                startBtn.disabled = false;
                stopBtn.disabled = true;
            }
        }

        function cleanupStream() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            streamActive = false;
            updateUI(false);
        }

        async function stopStream() {
            const streamKey = streamKeyInput.value.trim();
            try {
                const response = await fetch(`http://127.0.0.1:8080/stop-stream?streamKey=${encodeURIComponent(streamKey)}`, {
                    method: 'GET'
                });
                const result = await response.text();
                addMessage(result);
            } catch (error) {
                addMessage(`停止推流错误: ${error.message}`);
            } finally {
                cleanupStream();
            }
        }

        function addMessage(message) {
            const p = document.createElement('p');
            p.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            messagesDiv.appendChild(p);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
    </script>
</body>
</html>